<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="出库基本信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="80px">
            <px-row :gutter="16">
              <px-col :span="8">
                <px-form-item label="出库单号" prop="outNum">
                  <px-input v-model="formValue.outNum" placeholder="请输入出库单号" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="领用人" prop="recipientId">
                  <px-select-v2
                    v-model="formValue.recipientId"
                    filterable
                    clearable
                    :options="recipientIdList"
                    placeholder="请选择领用人"
                    @change="recipientIdChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="用途" prop="used">
                  <px-select v-model="formValue.used" placeholder="请选择用途" filterable clearable @change="usedChange">
                    <px-option v-for="item in usedList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="种类" prop="category">
                  <px-select v-model="formValue.category" placeholder="请选择种类" filterable clearable>
                    <px-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="关联单据" prop="billNum">
                  <px-input v-model="formValue.billNum" placeholder="请输入关联单据" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.category === 'sparePart'" :span="24">
                <px-row :gutter="16">
                  <px-col :span="8">
                    <px-form-item
                      label="设备编号"
                      prop="equipmentId"
                      :rules="{
                        required: true,
                        message: '设备选择不能为空',
                        trigger: 'change'
                      }"
                    >
                      <px-input
                        v-model="formValue.equipmentId"
                        placeholder="请点击选择"
                        maxlength="50"
                        disabled
                        style="width: calc(100% - 108px); margin-right: 8px"
                      />
                      <px-button type="primary" plain style="width: 100px" @click="selectDialogVisible = true">选择设备</px-button>
                    </px-form-item>
                  </px-col>
                  <px-col :span="8">
                    <px-form-item
                      label="设备名称"
                      prop="equipmentName"
                      :rules="{
                        required: true,
                        message: '设备选择不能为空',
                        trigger: 'change'
                      }"
                    >
                      <px-input v-model="formValue.equipmentName" placeholder="请点击选择" maxlength="50" disabled /> </px-form-item></px-col
                  ><px-col :span="8">
                    <px-form-item
                      label="设备位置"
                      prop="positionNameAll"
                      :rules="{
                        required: true,
                        message: '设备选择不能为空',
                        trigger: 'change'
                      }"
                    >
                      <px-input v-model="formValue.positionNameAll" placeholder="请点击选择" maxlength="50" disabled />
                    </px-form-item>
                  </px-col>
                </px-row>
              </px-col>
              <px-col v-if="formValue.category !== 'sparePart'" :span="24">
                <px-form-item
                  label="设备选择"
                  prop="equipmentList"
                  :rules="{
                    required: true,
                    message: '设备选择不能为空',
                    trigger: 'change'
                  }"
                >
                  <px-button type="primary" plain style="width: 100px" @click="selectEquip">选择设备</px-button>
                </px-form-item>
                <px-table :data="formValue.equipmentList" class="equip-table" size="small" border>
                  <px-table-column prop="eqpId" label="设备编号" min-width="160" show-overflow-tooltip />
                  <px-table-column prop="eqpName" label="设备名称" min-width="160" show-overflow-tooltip />
                  <px-table-column prop="positionNameAll" label="设备位置" min-width="160" show-overflow-tooltip />
                  <px-table-column fixed="right" label="操作" min-width="40" align="center">
                    <template #default="scope">
                      <px-tooltip content="删除" placement="top">
                        <px-button link type="danger" icon="Delete" @click="handleDeleteEquip(scope.$index)" />
                      </px-tooltip>
                    </template>
                  </px-table-column>
                </px-table>
              </px-col>
              <px-col :span="24">
                <px-row :gutter="16">
                  <px-col :span="8">
                    <px-form-item label="出库日期" prop="outDate">
                      <px-date-picker
                        v-model="formValue.outDate"
                        type="date"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择出库日期"
                        clearable
                        :disabled-date="disabledDate"
                      />
                      <!-- :disabled-hours="disabledHours"
                        :disabled-minutes="disabledMinutes"
                        :disabled-seconds="disabledSeconds" -->
                    </px-form-item>
                  </px-col>
                  <px-col :span="16">
                    <px-form-item label="备注" prop="remark">
                      <px-input v-model="formValue.remark" placeholder="请输入备注" maxlength="1000" clearable />
                    </px-form-item>
                  </px-col>
                </px-row>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="备件列表">
        <template v-slot:content>
          <div style="display: flex">
            <px-button style="margin-bottom: 8px" type="primary" @click="selectSparePart"
              >选择{{ formValue.category === "sparePart" ? "备件" : "耗材" }}</px-button
            >
            <px-button style="margin-right: 8px" type="primary" plain @click="templateDownload">下载模板</px-button>
            <BatchUpload url="/ifp/digitaltwins/api/v1/sparePartNew/inOutImportData" @updateUploadPage="addTableRow" />
          </div>
          <px-table :data="formValue.tableData" class="equip-table" size="small" height="280" border>
            <px-table-column
              v-for="(item, index) in tableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
            <px-table-column prop="quantity" label="出库数量" min-width="160" show-overflow-tooltip>
              <template #header>
                出库数量
                <px-icon style="cursor: pointer" @click="editQuantity">
                  <EditPen />
                </px-icon>
              </template>
              <template #default="scope">
                <div v-if="isQuantity">
                  {{ scope.row.quantity }}
                </div>
                <px-input-number v-else v-model.number="scope.row.quantity" :min="1" :max="scope.row.currentStock" size="small" />
              </template>
            </px-table-column>
            <px-table-column fixed="right" label="操作" min-width="144" align="center">
              <template #default="scope">
                <px-tooltip content="删除" placement="top">
                  <px-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog :params="sparePartsPrams" :visible="dialogVisible" @closeDialog="closeDialog" @addTableRow="addTableRow" />
  <!-- 选择设备弹窗 -->
  <EquipIdSelectDialog
    :multiple="formValue.category === 'consumable'"
    :visible="selectDialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    @closeEquipDialog="closeSelectDialog"
    @changeEqpId="addEquipId"
  />
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import {
  addSparePartsOutbound,
  editSparePartsOutbound,
  getSparePartsOutbound,
  querySparePartsLedgerNew,
  querySparePartsOutboundNum
} from "@/api/equip/spareParts";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import BatchUpload from "./BatchUpload.vue";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch, getCurrentInstance } from "vue";
import AddSparePartsDialog from "./AddSparePartsDialog.vue";
const { proxy }: any = getCurrentInstance();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 备件弹窗参数
const sparePartsPrams = computed(() => {
  const { className, category, equipmentId, equipmentList } = formValue.value;
  const ids = equipmentList?.map(item => item.eqpId) || [];
  const params = {
    className: className,
    category: category,
    eqpIds: category === "sparePart" ? [equipmentId] : ids
  };
  return params;
});
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    outNum: "",
    recipientId: null,
    recipientName: "",
    equipmentId: "",
    equipmentName: "",
    positionNameAll: "",
    equipmentList: [],
    used: "wx",
    category: "sparePart",
    className: "",
    billNum: "",
    outDate: "",
    remark: "",
    tableData: []
  },
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "140", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "120" },
    { prop: "supplyModel", label: "厂商型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "120" },
    { prop: "currentStock", label: "库存量", minWidth: "120", showOverflowTooltip: true }
  ],
  recipientIdList: [],
  usedList: [],
  categoryList: [],
  isQuantity: true,
  selectDialogVisible: false,
  dialogVisible: false,
  systemCodes: []
});
const { formValue, tableColumns, recipientIdList, usedList, categoryList, isQuantity, selectDialogVisible, dialogVisible, systemCodes } =
  toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  outNum: [{ required: true, message: "出库单号不能为空", trigger: "blur" }],
  recipientId: [{ required: true, message: "领用人不能为空", trigger: "change" }],
  used: [{ required: true, message: "用途不能为空", trigger: "change" }],
  category: [{ required: true, message: "种类不能为空", trigger: "change" }],
  outDate: [{ required: true, message: "出库日期不能为空", trigger: "blur" }]
}));
// 点击选择设备
const selectEquip = () => {
  const { className } = formValue.value;
  if (!className) {
    formRef.value.validateField("className");
  } else {
    selectDialogVisible.value = true;
  }
};
// 点击选择备件/耗材
const selectSparePart = () => {
  const { className, category, equipmentId, equipmentList } = formValue.value;
  if (!className || !category || (!equipmentId && equipmentList.length === 0)) {
    formRef.value.validateField("className");
    formRef.value.validateField("category");
    formRef.value.validateField("equipmentId");
    formRef.value.validateField("equipmentName");
    formRef.value.validateField("positionNameAll");
    formRef.value.validateField("equipmentList");
  } else {
    dialogVisible.value = true;
  }
};
// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 禁用时
const disabledHours = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用分
const disabledMinutes = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用秒
const disabledSeconds = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};

// 监视isMain和isView值
watch(isMain, async val => {
  formRef.value.resetFields();
  if (!val && !props.isView) {
    formRef.value.resetFields();
    queryRecipientIdSelect();
    queryUsedSelect();
    queryCategory();
    isQuantity.value = true;
    if (props.drawerType === "ledger") {
      const sparesList = await querySparePartsLedgerNew({
        pageNum: 1,
        pageSize: 20,
        spareNameOrCode: props.sparePartsId,
        stockAlarm: false
      });
      const spareData = sparesList?.data[0] || {};
      formValue.value.tableData = sparesList?.data;
      const outNum = await querySparePartsOutboundNum({});
      // const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      const { className, category } = spareData;
      formValue.value = {
        ...formValue.value,
        outNum,
        className,
        category,
        used: category === "sparePart" ? "wx" : "by",
        // recipientId: userInfo.userId,
        recipientId: "",
        outDate: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
        // recipientName: userInfo.username + "-" + userInfo.realName,
        recipientName: "",
        tableData: [sparesList?.data[0]]
      };
    } else if (props.drawerType === "add") {
      const data = await querySparePartsOutboundNum({});
      formValue.value.outNum = data;
      formValue.value.recipientId = null;
      formValue.value.recipientName = "";
      formValue.value.equipmentId = "";
      formValue.value.equipmentName = "";
      formValue.value.positionNameAll = "";
      formValue.value.equipmentList = [];
      formValue.value.used = "wx";
      formValue.value.category = "sparePart";
      formValue.value.className = "";
      formValue.value.billNum = "";
      formValue.value.outDate = "";
      formValue.value.remark = "";
      formValue.value.tableData = [];
      delete formValue.value.id;
    } else if (props.drawerType === "edit") {
      getDetail();
    }
  } else {
    formValue.value = {
      id: "",
      outNum: "",
      recipientId: null,
      recipientName: "",
      equipmentId: "",
      equipmentName: "",
      positionNameAll: "",
      equipmentList: [],
      used: "wx",
      category: "sparePart",
      className: "",
      billNum: "",
      outDate: "",
      remark: "",
      tableData: []
    };
  }
});
watch(
  () => formValue.value.used,
  val => {
    if (val === "wx") {
      formValue.value.category = "sparePart";
    } else if (val === "by") {
      formValue.value.category = "consumable";
    }
  }
);
// 领用人下拉框
const queryRecipientIdSelect = async () => {
  recipientIdList.value = await getEmployeeIdAndName();
};
// 获取principalName
const recipientIdChange = val => {
  const arr = recipientIdList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.recipientName = arr[0].label;
  }
};
// 用途改变
const usedChange = () => {
  formValue.value.tableData = [];
};
// 用途下拉框
const queryUsedSelect = async () => {
  usedList.value = [];
  const params = {
    typeCode: "used"
  };
  const data = await queryDictData(params);
  usedList.value = data;
};
// 种类下拉框
const queryCategory = async () => {
  categoryList.value = [];
  const params = {
    typeCode: "typeCategory"
  };
  const data = await queryDictData(params);
  categoryList.value = data;
};
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.sparePartsId
  };
  const data: any = await getSparePartsOutbound(params);
  formValue.value.id = data.id;
  formValue.value.outNum = data.outNum;
  formValue.value.recipientId = data.recipientId;
  formValue.value.recipientName = data.recipientName;
  if (data.category === "sparePart") {
    formValue.value.equipmentId = data.equipmentInfoDTOList[0]?.eqpId;
    formValue.value.equipmentName = data.equipmentInfoDTOList[0]?.eqpName;
    formValue.value.positionNameAll = data.equipmentInfoDTOList[0]?.positionNameAll;
  } else {
    formValue.value.equipmentList = data.equipmentInfoDTOList;
  }
  formValue.value.used = data.used;
  formValue.value.className = data.className;
  formValue.value.billNum = data.billNum;
  formValue.value.outDate = data.outDate;
  formValue.value.remark = data.remark;
  formValue.value.tableData = data.inventoryDetailDTOList;
};
// 编辑数量
const editQuantity = () => {
  isQuantity.value = !isQuantity.value;
};
// 删除备件表格某一行
const handleDelete = (index: any) => {
  formValue.value.tableData.splice(index, 1);
};
// 删除设备表格某一行
const handleDeleteEquip = index => {
  formValue.value.equipmentList.splice(index, 1);
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 关闭子级设备dialog弹窗
const closeSelectDialog = () => {
  selectDialogVisible.value = false;
};
// 添加设备id
const addEquipId = equipDetail => {
  if (formValue.value.category === "sparePart") {
    formValue.value.className = equipDetail?.className || "";
    formValue.value.equipmentId = equipDetail?.eqpId || "";
    formValue.value.equipmentName = equipDetail?.eqpName || "";
    formValue.value.positionNameAll = equipDetail?.positionNameAll || "";
  } else {
    equipDetail.forEach(item => {
      const flag = formValue.value.equipmentList?.find(equip => equip.eqpId === item.eqpId);
      if (!flag) {
        formValue.value.equipmentList.push({
          eqpName: item.eqpName,
          eqpId: item.eqpId,
          positionNameAll: item.positionNameAll
        });
      }
    });
    formRef.value.validateField("equipmentList");
  }
  if (props.drawerType !== "ledger") {
    formValue.value.tableData = [];
  }
};
// 选择备件后添加表格数据
const addTableRow = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        arr2.push(item);
      }
    });
    formValue.value.tableData = [...arr2, ...formValue.value.tableData];
  }
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { tableData, category, equipmentId, equipmentList, ...rest } = formValue.value;
      if (tableData && tableData.length > 0) {
        const arr = [];
        tableData.forEach(item => {
          arr.push({
            parePartId: item.id,
            quantity: item.quantity
          });
        });
        if (arr && arr.length > 0) {
          const flag = arr.every(item => {
            return item.quantity !== "" && item.quantity !== null;
          });
          if (!flag) {
            PxMessage.error("您尚有未填写的出库数量，请填写完成后进行提交！");
            return;
          }
        }
        const ids = equipmentList.map(item => item.eqpId);
        const list = category === "sparePart" ? [equipmentId] : ids;
        const params = { ...rest, category, equipmentIdList: list, inventoryDetailList: arr };
        if (props.drawerType === "add" || props.drawerType === "ledger") {
          await addSparePartsOutbound(params);
          PxMessage.success("创建成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editSparePartsOutbound(params);
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      } else {
        PxMessage.error("备件列表不能为空");
      }
    }
  });
};
// 下载模版
const templateDownload = async () => {
  proxy.download("get", "/digitaltwins/api/v1/sparePartNew/inOutTemplateDownLoad", {}, "备件出入库数据模板.xlsx");
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  if (!isOnlyClass) {
    formValue.value.equipmentName = "";
    formValue.value.equipmentId = "";
    formValue.value.positionNameAll = "";
    formValue.value.equipmentList = [];
    formValue.value.tableData = [];
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

.flex-row {
  display: flex;
  align-items: center;
}

.row-item {
  width: 100%;
}

.btn-group {
  .add-btn,
  .delete-btn {
    cursor: pointer;
  }

  .delete-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    font-size: 12px;
    color: #ef4444;
    border: 1.8px solid #ef4444;
    border-radius: 50%;
  }

  .add-btn {
    font-size: 24px;
    color: #3b82f6;
  }
}
</style>
